package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"wms/models"
	"wms/settings"
)

var DB *gorm.DB

// Init 初始化MySQL连接
func Init(cfg *settings.MySQLConfig) (err error) {
	// "user:password@tcp(host:port)/dbname"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DB)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return
	}
	err = db.AutoMigrate(&models.UserBasic{}, &models.RoleBasic{},
		&models.FunctionBasic{}, &models.MenuBasic{},
		&models.RoleMenu{}, &models.RoleFunction{})
	if err != nil {
		return
	}
	DB = db
	return err
}
